package gui;

import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
import javax.swing.border.LineBorder;

import matrix.Iterative;
import matrix.Matrix;
import matrix.SSLE;
import matrix.Utils;

public class MainFrame extends JFrame {
	
	private static final long serialVersionUID = 2292455670620751734L;
	
	private JPanel contentPane;
	public JScrollPane scrollPane;
	public InputPanel inputPanel;
	
	private JMenuBar menuBar;
	public JPanel panel;
	public JPanel panel_1;
	public JButton button;
	public JScrollPane scrollPane_1;
	public JPanel panel_2;
	private JPanel panel_3;
	private JMenu mnFile;
	private JMenu mnHelp;
	private JMenuItem mntmImport;
	private JSeparator separator;
	private JMenuItem mntmExit;
	private JMenuItem mntmGuide;
	private JSeparator separator_1;
	private JMenuItem mntmAbout;
	
	private LatexDisplay pnlProblem = new LatexDisplay("Problem");
	private LatexDisplay pnlSoln;
	private SummaryDisplay summaryDisplay;
	
	public static void main(String[] args) throws Exception {
		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainFrame frame = new MainFrame("SSLE v1.0");
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	public MainFrame(String string) {
		setTitle(string);
		init();
	}
	
	private void init() {
		setFocusable(false);
		menuBar = new JMenuBar();
		menuBar.setFocusable(false);
		setJMenuBar(menuBar);
		
		mnFile = new JMenu("File");
		menuBar.add(mnFile);
		
		mntmImport = new JMenuItem("Import");
		mntmImport.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser fc = new JFileChooser("import");
				try {
					if (fc.showOpenDialog(inputPanel) == JFileChooser.APPROVE_OPTION) {
						// get
						ArrayList<ArrayList<Double>> lst2d = new ArrayList<ArrayList<Double>>();
						Scanner scn = new Scanner(fc.getSelectedFile());
						while (scn.hasNext()) {
							Scanner inScn = new Scanner(scn.nextLine());
							lst2d.add(new ArrayList<Double>());
							while (inScn.hasNext())
								lst2d.get(lst2d.size() - 1).add(inScn.nextDouble());
							inScn.close();
						}
						scn.close();
						// fill table
						inputPanel.setTable(lst2d);
					}
				} catch (FileNotFoundException e1) {
					JOptionPane.showMessageDialog(inputPanel, "Can't import file: " + fc.getSelectedFile().getAbsolutePath());
				}
			}
		});
		mnFile.add(mntmImport);
		
		separator = new JSeparator();
		mnFile.add(separator);
		
		mntmExit = new JMenuItem("Exit");
		mntmExit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(ABORT);
			}
		});
		mnFile.add(mntmExit);
		
		mnHelp = new JMenu("Help");
		menuBar.add(mnHelp);
		
		mntmGuide = new JMenuItem("Guide");
		mntmGuide.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					Desktop.getDesktop().open(new File("doc\\Guide.pdf"));
				} catch (Exception ex) {
					JOptionPane.showMessageDialog(contentPane, ex.getMessage());
				}
			}
		});
		mnHelp.add(mntmGuide);
		
		separator_1 = new JSeparator();
		mnHelp.add(separator_1);
		
		mntmAbout = new JMenuItem("About");
		mntmAbout.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(contentPane, "SSLE v1.0\nAuthors:\nA.Salah - M. AboShamaa - M. Bassem - M. Ghareeb - Pola");
			}
		});
		mnHelp.add(mntmAbout);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 800, 500);
		contentPane = new JPanel();
		contentPane.setFocusable(false);
		setContentPane(contentPane);
		
		scrollPane = new JScrollPane();
		scrollPane.setFocusable(false);
		scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		
		panel = new JPanel();
		panel.setFocusable(false);
		
		panel_1 = new JPanel();
		panel_1.setFocusable(false);
		
		scrollPane_1 = new JScrollPane();
		scrollPane_1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scrollPane_1.setFocusable(false);
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(gl_panel.createParallelGroup(Alignment.LEADING).addGroup(
				gl_panel.createSequentialGroup().addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 10, GroupLayout.PREFERRED_SIZE).addGap(1)
						.addComponent(scrollPane_1, GroupLayout.DEFAULT_SIZE, 497, Short.MAX_VALUE)));
		gl_panel.setVerticalGroup(gl_panel.createParallelGroup(Alignment.LEADING).addComponent(panel_1, GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
				.addComponent(scrollPane_1, GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE));
		
		panel_2 = new JPanel();
		scrollPane_1.setViewportView(panel_2);
		panel_2.setLayout(new BorderLayout(0, 0));
		pnlProblem.latexPnl.setPreferredSize(new Dimension(256, 128));
		pnlProblem.setPreferredSize(new Dimension(256, 192));
		
		panel_2.add(pnlProblem, BorderLayout.NORTH);
		
		panel_3 = new JPanel();
		panel_2.add(panel_3, BorderLayout.CENTER);
		panel_3.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_4 = new JPanel();
		panel_3.add(panel_4, BorderLayout.CENTER);
		panel_4.setLayout(new BorderLayout(0, 0));
		
		summaryDisplay = new SummaryDisplay();
		summaryDisplay.xScrlPane.setPreferredSize(new Dimension(275, 128));
		summaryDisplay.panel.setPreferredSize(new Dimension(512, 512));
		summaryDisplay.setPreferredSize(new Dimension(256, 128));
		panel_4.add(summaryDisplay, BorderLayout.NORTH);
		
		pnlSoln = new LatexDisplay((String) null);
		pnlSoln.setPreferredSize(new Dimension(256, 384));
		pnlSoln.setSize(new Dimension(256, 256));
		pnlSoln.setTitle("Solution \\; steps");
		panel_3.add(pnlSoln, BorderLayout.NORTH);
		panel_1.setLayout(new BorderLayout(0, 0));
		
		button = new JButton("");
		button.setFocusable(false);
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent paramActionEvent) {
				do_button_actionPerformed(paramActionEvent);
			}
		});
		panel_1.add(button, BorderLayout.CENTER);
		panel.setLayout(gl_panel);
		
		inputPanel = new InputPanel();
		inputPanel.btnSolve.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				solve(false);
			}
		});
		inputPanel.btnSteps.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				solve(true);
			}
		});
		inputPanel.scrl.setPreferredSize(new Dimension(452, 256));
		inputPanel.setPreferredSize(new Dimension(256, 400));
		scrollPane.setViewportView(inputPanel);
		contentPane.setLayout(new BorderLayout(0, 0));
		contentPane.add(panel);
		contentPane.add(scrollPane, BorderLayout.WEST);
		
		JLabel lblNewLabel = new JLabel(" ");
		lblNewLabel.setBorder(new LineBorder(SystemColor.control));
		contentPane.add(lblNewLabel, BorderLayout.SOUTH);
	}
	
	protected void do_button_actionPerformed(ActionEvent paramActionEvent) {
		scrollPane.setVisible(!scrollPane.isVisible());
		revalidate();
	}
	
	@SuppressWarnings("unchecked")
	private void solve(boolean buildSteps) {
		try {
			//
			SSLE ss = (SSLE) inputPanel.comboBox_1.getSelectedItem();
			int type = Utils.get((String) inputPanel.comboBox.getSelectedItem());
			//
			if (ss instanceof Iterative)
				((Iterative) ss).set(new Matrix(new String[][] { { "1" }, { "1" }, { "1" } }, type), inputPanel.getIterations(), 0);
			ss.solve(inputPanel.getMatrixA(), inputPanel.getMatrixB(), buildSteps);
			summaryDisplay.update(ss);
			if (pnlProblem.isCollapsed() ^ buildSteps)
				pnlProblem.toggleCollapse();
			if (pnlSoln.isCollapsed() ^ buildSteps)
				pnlSoln.toggleCollapse();
			if (buildSteps) {
				ArrayList<String> sln = ss.steps();
				ArrayList<String> problem = ((ArrayList<String>) sln.clone());
				problem.clear();
				for (int i = 0; i < 3; i++)
					problem.add(sln.remove(0));
				pnlProblem.setContent(problem.toString());
				pnlSoln.setContent(sln.toString());
			}
		} catch (Exception e) {
			JOptionPane.showMessageDialog(this, e.getMessage());
		}
	}
	
}
